﻿using System;
using System.Data.SQLite;
using System.IO;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace Amgine
{
    public partial class UpdateDBProcessForm : Form
    {
        #region public

        private const int TYPE_RESET_PASSWORD = 1;
        private const int TYPE_EXPORT = 2;
        private const int TYPE_IMPORT = 3;

        private int type;
        private string path;
        private JsonObjectKeeper keeper;

        private string oldPsw;
        private string newPsw;
        private byte[] oldKey;
        private byte[] newKey;

        private delegate void SetLabelValueCallback(string text);
        private delegate void SetProgressBarValueCallback(int value);
        private delegate void CompleteCallback();

        public UpdateDBProcessForm()
        {
            InitializeComponent();
            type = -1;
        }

        private void UpdateDBProcessForm_Shown(object sender, EventArgs e)
        {
            Thread thread = null;
            switch (type)
            {
                case TYPE_RESET_PASSWORD:
                    thread = new Thread(new ThreadStart(updateDBWhenResetPassword));
                    break;
                case TYPE_EXPORT:
                    thread = new Thread(new ThreadStart(exportFromDB));
                    break;
                case TYPE_IMPORT:
                    thread = new Thread(new ThreadStart(updateDBWhenImport));
                    break;
                default: return;
            }
            thread.Start();
        }

        private void OperationCompleted()
        {
            DialogResult = DialogResult.OK;
            Close();
        }

        public void setExport(string path)
        {
            this.path = path;
            type = TYPE_EXPORT;
            Name = "正在导出";
            SetLabelValue("正在导出");
        }

        public void setImport(string path)
        {
            this.path = path;
            type = TYPE_IMPORT;
            Name = "正在导入";
            SetLabelValue("正在导入");
        }

        public void setResetPassword(string oldPsw, string newPsw)
        {
            this.oldPsw = oldPsw;
            this.newPsw = newPsw;
            oldKey = EncryptDecryptUtils.prepareMD5ByteArray32(oldPsw);
            newKey = EncryptDecryptUtils.prepareMD5ByteArray32(newPsw);
            type = TYPE_RESET_PASSWORD;
        }

        #endregion

        #region file sys

        private void exportFromDB()
        {
            keeper = new JsonObjectKeeper();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_ACCOUNT + "】，（第1个，共9个）……");
            SetProgressBarValue(0);
            keeper.AccountList = DBHelper.listAllAccountFromDB();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_ACCOUNT_GROUP + "】，（第2个，共9个）……");
            SetProgressBarValue(8);
            keeper.AccountGroupList = DBHelper.listAllAccountGroup();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_DICTIONARY + "】，（第3个，共9个）……");
            SetProgressBarValue(16);
            keeper.DictionaryList = DBHelper.listAllDictionary();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_LINKMAN + "】，（第4个，共9个）……");
            SetProgressBarValue(24);
            keeper.LinkmanList = DBHelper.listAllLinkmanFromDB();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_LINKMAN_GROUP + "】，（第5个，共9个）……");
            SetProgressBarValue(32);
            keeper.LinkmanGroupList = DBHelper.listAllLinkmanGroup();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_LINKMAN_DETAILS + "】，（第6个，共9个）……");
            SetProgressBarValue(40);
            keeper.LinkmanDetailsList = DBHelper.listAllLinkmanDetailsFromDB();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_TOOL + "】，（第7个，共9个）……");
            SetProgressBarValue(48);
            keeper.ToolList = DBHelper.listAllToolsFromDB();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_TOOL_GROUP + "】，（第8个，共9个）……");
            SetProgressBarValue(56);
            keeper.ToolGroupList = DBHelper.listAllToolGroup();

            SetLabelValue("正在提取表【" + DBHelper.TABLE_NOTE + "】，（第9个，共9个）……");
            SetProgressBarValue(64);
            keeper.NoteList = DBHelper.listAllNote();

            SetLabelValue("正在生成文件内容……");
            SetProgressBarValue(72);
            string json = new JavaScriptSerializer().Serialize(keeper);

            SetLabelValue("正在保存文件……");
            SetProgressBarValue(80);
            Stream stream = File.OpenWrite(path);
            using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
            {
                writer.Write(json);
            }

            SetLabelValue("正在校验……");
            SetProgressBarValue(90);
            Thread.Sleep(1000);

            SetLabelValue("文件成功保存至" + path);
            SetProgressBarValue(100);
            Thread.Sleep(1000);
            SetFormClose();
        }

        private void updateDBWhenImport()
        {
            SetLabelValue("正在读取文件……");
            SetProgressBarValue(0);
            string json = null;
            Stream stream = File.OpenRead(path);
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                json = reader.ReadToEnd();
            }

            SetLabelValue("正在分析文件……");
            SetProgressBarValue(10);
            keeper = (JsonObjectKeeper)(new JavaScriptSerializer().Deserialize(json,typeof(JsonObjectKeeper)));

            using (SQLiteTransaction tran = DBHelper.BASE_SQLITE_CONNECTION.BeginTransaction())
            {
                SetLabelValue("正在更新表【" + DBHelper.TABLE_ACCOUNT + "】，（第1个，共9个）……");
                SetProgressBarValue(20);
                importAccount();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_ACCOUNT_GROUP + "】，（第2个，共9个）……");
                SetProgressBarValue(28);
                importAccountGroup();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_DICTIONARY + "】，（第3个，共9个）……");
                SetProgressBarValue(36);
                importDictionary();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_LINKMAN + "】，（第4个，共9个）……");
                SetProgressBarValue(44);
                importLinkman();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_LINKMAN_DETAILS + "】，（第5个，共9个）……");
                SetProgressBarValue(52);
                importLinkmanDetails();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_LINKMAN_GROUP + "】，（第6个，共9个）……");
                SetProgressBarValue(60);
                importLinkmanGroup();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_TOOL + "】，（第7个，共9个）……");
                SetProgressBarValue(68);
                importTools();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_TOOL_GROUP + "】，（第8个，共9个）……");
                SetProgressBarValue(76);
                importToolGroup();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_NOTE + "】，（第9个，共9个）……");
                SetProgressBarValue(84);
                importNote();

                tran.Commit();
            }

            SetLabelValue("正在校验……");
            SetProgressBarValue(92);
            Thread.Sleep(1000);

            SetLabelValue("更新成功完成。");
            SetProgressBarValue(100);
            Thread.Sleep(1000);
            SetFormClose();
        }

        private void importNote()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_NOTE + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_NOTE
                + " VALUES (NULL,@title,@info,@ct,@ut); ";
            foreach (Note note in keeper.NoteList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@title", note.Title),
                    new SQLiteParameter("@info", note.Info),
                    new SQLiteParameter("@ct", note.CreateTime),
                    new SQLiteParameter("@ut", note.UpdateTime)
                });
                cmd.ExecuteNonQuery();
            }
        }

        private void importToolGroup()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_TOOL_GROUP + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_TOOL_GROUP
                + " VALUES (NULL,@title,@remark); ";
            foreach (ToolGroup group in keeper.ToolGroupList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@title", group.Title),
                    new SQLiteParameter("@remark", group.Remark)
                });
                cmd.ExecuteNonQuery();
            }
        }

        private void importTools()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_TOOL + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_TOOL
                + " VALUES (NULL,@name,@remark,@group); ";
            foreach (Tool tool in keeper.ToolList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@group", tool.GroupId),
                    new SQLiteParameter("@name", tool.Name),
                    new SQLiteParameter("@remark", tool.Remark)
                });
                cmd.ExecuteNonQuery();
            }
        }

        private void importLinkmanGroup()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_LINKMAN_GROUP + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_LINKMAN_GROUP
                + " VALUES (NULL,@name,@remark); ";
            foreach (LinkmanGroup group in keeper.LinkmanGroupList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@name", EncryptDecryptUtils.DES3Encrypt(group.Name, EncryptDecryptUtils.GLOBAL_INIT_VAR)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(group.Remark, EncryptDecryptUtils.GLOBAL_INIT_VAR))
                });
                cmd.ExecuteNonQuery();
            }
        }

        private void importLinkmanDetails()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_LINKMAN_DETAILS + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_LINKMAN_DETAILS
                + " VALUES (NULL,@type,@info,@remark,@linkman); ";
            foreach (LinkmanDetails detail in keeper.LinkmanDetailsList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@linkman", detail.LinkmanId),
                    new SQLiteParameter("@type", detail.Type),
                    new SQLiteParameter("@info", EncryptDecryptUtils.DES3Encrypt(detail.Info, EncryptDecryptUtils.GLOBAL_INIT_VAR)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(detail.Remark, EncryptDecryptUtils.GLOBAL_INIT_VAR))
                });
                cmd.ExecuteNonQuery();
            }
        }

        private void importLinkman()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_LINKMAN + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_LINKMAN
                + " VALUES (NULL,@group,@name,@remark); ";
            foreach (Linkman linkman in keeper.LinkmanList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@group", linkman.GroupId),
                    new SQLiteParameter("@name", EncryptDecryptUtils.DES3Encrypt(linkman.Name, EncryptDecryptUtils.GLOBAL_INIT_VAR)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(linkman.Remark, EncryptDecryptUtils.GLOBAL_INIT_VAR))
                });
                cmd.ExecuteNonQuery();
            }
        }

        private void importDictionary()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_DICTIONARY + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_DICTIONARY
                + " VALUES (NULL,@type,@code,@info,@flag); ";
            foreach (Dictionary dictionary in keeper.DictionaryList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@code", (dictionary.IsEncrypted ? EncryptDecryptUtils.DES3Encrypt(dictionary.Code, EncryptDecryptUtils.GLOBAL_INIT_VAR) : dictionary.Code)),
                    new SQLiteParameter("@info", (dictionary.IsEncrypted ? EncryptDecryptUtils.DES3Encrypt(dictionary.Info, EncryptDecryptUtils.GLOBAL_INIT_VAR) : dictionary.Info)),
                    new SQLiteParameter("@type", dictionary.Type),
                    new SQLiteParameter("@flag", dictionary.IsEncrypted)
                });
                cmd.ExecuteNonQuery();
            }
        }

        private void importAccountGroup()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_ACCOUNT_GROUP + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_ACCOUNT_GROUP
                + " VALUES (NULL,@title,@remark); ";
            foreach (AccountGroup group in keeper.AccountGroupList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@title", EncryptDecryptUtils.DES3Encrypt(group.Title,EncryptDecryptUtils.GLOBAL_INIT_VAR)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(group.Remark,EncryptDecryptUtils.GLOBAL_INIT_VAR))
                });
                cmd.ExecuteNonQuery();
            }
        }

        private void importAccount()
        {
            SQLiteCommand cmd = new SQLiteCommand(" DELETE FROM "
                + DBHelper.TABLE_ACCOUNT + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            cmd.ExecuteNonQuery();

            cmd.CommandText = " INSERT INTO " + DBHelper.TABLE_ACCOUNT
                + " VALUES (NULL,@title,@name,@psw,@remark,@group); ";
            foreach (Account account in keeper.AccountList)
            {
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@group", account.GroupId),
                    new SQLiteParameter("@title", EncryptDecryptUtils.DES3Encrypt(account.Title, EncryptDecryptUtils.GLOBAL_INIT_VAR)),
                    new SQLiteParameter("@name", EncryptDecryptUtils.DES3Encrypt(account.Name, EncryptDecryptUtils.GLOBAL_INIT_VAR)),
                    new SQLiteParameter("@psw", EncryptDecryptUtils.DES3Encrypt(account.Password, EncryptDecryptUtils.GLOBAL_INIT_VAR)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(account.Remark, EncryptDecryptUtils.GLOBAL_INIT_VAR))
                });
                cmd.ExecuteNonQuery();
            }
        }

        #endregion

        #region reset password

        private void updateDBWhenResetPassword()
        {
            using (SQLiteTransaction tran = DBHelper.BASE_SQLITE_CONNECTION.BeginTransaction())
            {
                SetLabelValue("正在更新表【" + DBHelper.TABLE_ACCOUNT + "】，（第1个，共6个）……");
                SetProgressBarValue(0);
                resetAccountPassword();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_ACCOUNT_GROUP + "】，（第2个，共6个）……");
                SetProgressBarValue(15);
                resetAccountGroupPassword();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_LINKMAN + "】，（第3个，共6个）……");
                SetProgressBarValue(30);
                resetLinkmanPassword();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_LINKMAN_GROUP + "】，（第4个，共6个）……");
                SetProgressBarValue(45);
                resetLinkmanGroupPassword();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_LINKMAN_DETAILS + "】，（第5个，共6个）……");
                SetProgressBarValue(60);
                resetLinkmanDetailsPassword();

                SetLabelValue("正在更新表【" + DBHelper.TABLE_DICTIONARY + "】，（第6个，共6个）……");
                SetProgressBarValue(75);
                resetDictionaryPassword();

                tran.Commit();
            }

            SetLabelValue("正在校验……");
            SetProgressBarValue(90);
            Thread.Sleep(1000);

            SetLabelValue("更新成功完成。");
            SetProgressBarValue(100);
            Thread.Sleep(1000);
            SetFormClose();
        }

        private bool resetDictionaryPassword()
        {
            int ret = 0;
            SQLiteCommand read = new SQLiteCommand(" SELECT * FROM "
                + DBHelper.TABLE_DICTIONARY + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            SQLiteDataReader reader = read.ExecuteReader();

            SQLiteCommand cmd = new SQLiteCommand(" UPDATE "
                + DBHelper.TABLE_DICTIONARY + " SET "
                + DBHelper.DICTIONARY_TYPE + " =@type, "
                + DBHelper.DICTIONARY_CODE + " =@code, "
                + DBHelper.DICTIONARY_INFO + " =@info, "
                + DBHelper.DICTIONARY_IS_ENCRYPTED + " =@flag "
                + " WHERE " + DBHelper.PKID + " =@id; ",
                DBHelper.BASE_SQLITE_CONNECTION);

            bool flag = false;
            string code = null;
            string info = null;
            int id = -1;
            int type = -1;

            while (reader.Read())
            {
                flag = (reader.GetInt32(4) != 0);
                id = reader.GetInt32(0);
                type = reader.GetInt32(1);
                code = reader.GetString(2);
                info = reader.GetString(3);

                if (flag)
                {
                    code = EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(code, oldKey), newKey);
                    info = EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(info, oldKey), newKey);
                }

                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@id", id),
                    new SQLiteParameter("@code", code),
                    new SQLiteParameter("@info", info),
                    new SQLiteParameter("@type", type),
                    new SQLiteParameter("@flag", flag)
                });

                ret += cmd.ExecuteNonQuery();
            }

            return ret != 0;
        }

        private bool resetLinkmanPassword()
        {
            int ret = 0;
            SQLiteCommand read = new SQLiteCommand(" SELECT * FROM "
                + DBHelper.TABLE_LINKMAN + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            SQLiteDataReader reader = read.ExecuteReader();

            int id = -1;
            SQLiteCommand cmd = new SQLiteCommand(" UPDATE "
                    + DBHelper.TABLE_LINKMAN + " SET "
                    + DBHelper.LINKMAN_NAME + " =@name, "
                    + DBHelper.LINKMAN_REMARK + " =@remark "
                    + " WHERE " + DBHelper.PKID + " =@id; ",
                    DBHelper.BASE_SQLITE_CONNECTION);

            while (reader.Read())
            {
                id = reader.GetInt32(0);
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@id", id),
                    new SQLiteParameter("@name", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(2), oldKey), newKey)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(3), oldKey), newKey))
                });
                ret += cmd.ExecuteNonQuery();

            }
            return ret != 0;
        }

        private bool resetLinkmanGroupPassword()
        {
            int ret = 0;
            SQLiteCommand read = new SQLiteCommand(" SELECT * FROM "
                + DBHelper.TABLE_LINKMAN_GROUP + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            SQLiteDataReader reader = read.ExecuteReader();

            int id = -1;
            SQLiteCommand cmd = new SQLiteCommand(" UPDATE "
                + DBHelper.TABLE_LINKMAN_GROUP + " SET "
                + DBHelper.LINKMAN_GROUP_NAME + " =@name, "
                + DBHelper.LINKMAN_GROUP_REMARK + " =@remark "
                + " WHERE " + DBHelper.PKID + " =@id; ",
                DBHelper.BASE_SQLITE_CONNECTION);

            while (reader.Read())
            {
                id = reader.GetInt32(0);
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@id", id),
                    new SQLiteParameter("@name", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(1), oldKey), newKey)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(2), oldKey), newKey))
                });
                ret += cmd.ExecuteNonQuery();
            }
            return ret != 0;
        }

        private bool resetLinkmanDetailsPassword()
        {
            int ret = 0;
            SQLiteCommand read = new SQLiteCommand(" SELECT * FROM "
                + DBHelper.TABLE_LINKMAN_DETAILS + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            SQLiteDataReader reader = read.ExecuteReader();

            int id = -1;
            SQLiteCommand cmd = new SQLiteCommand(" UPDATE "
                + DBHelper.TABLE_LINKMAN_DETAILS + " SET "
                + DBHelper.LINKMAN_DETAILS_INFO + " =@info, "
                + DBHelper.LINKMAN_DETAILS_REMARK + " =@remark "
                + " WHERE " + DBHelper.PKID + " =@id; ",
                DBHelper.BASE_SQLITE_CONNECTION);

            while (reader.Read())
            {
                id = reader.GetInt32(0);
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@id", id),
                    new SQLiteParameter("@info", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(2), oldKey), newKey)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(3), oldKey), newKey))
                });
                ret += cmd.ExecuteNonQuery();
            }
            return ret != 0;
        }

        private bool resetAccountPassword()
        {
            int ret = 0;
            SQLiteCommand read = new SQLiteCommand(" SELECT * FROM "
                + DBHelper.TABLE_ACCOUNT + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            SQLiteDataReader reader = read.ExecuteReader();

            int id = -1;
            SQLiteCommand cmd = new SQLiteCommand(" UPDATE "
                + DBHelper.TABLE_ACCOUNT + " SET "
                + DBHelper.ACCOUNT_TITLE + " =@title, "
                + DBHelper.ACCOUNT_NAME + " =@name, "
                + DBHelper.ACCOUNT_PASSWORD + " =@psw, "
                + DBHelper.ACCOUNT_REMARK + " =@remark "
                + " WHERE " + DBHelper.PKID + " =@id; ",
                DBHelper.BASE_SQLITE_CONNECTION);

            while (reader.Read())
            {
                id = reader.GetInt32(0);
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@id", id),
                    new SQLiteParameter("@title", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(1), oldKey), newKey)),
                    new SQLiteParameter("@name", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(2), oldKey), newKey)),
                    new SQLiteParameter("@psw", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(3), oldKey), newKey)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(4), oldKey), newKey))
                });
                ret += cmd.ExecuteNonQuery();
            }
            return ret != 0;
        }

        private bool resetAccountGroupPassword()
        {
            int ret = 0;
            SQLiteCommand read = new SQLiteCommand(" SELECT * FROM "
                + DBHelper.TABLE_ACCOUNT_GROUP + " ; ", DBHelper.BASE_SQLITE_CONNECTION);
            SQLiteDataReader reader = read.ExecuteReader();

            int id = -1;
            SQLiteCommand cmd = new SQLiteCommand(" UPDATE "
                + DBHelper.TABLE_ACCOUNT_GROUP + " SET "
                + DBHelper.ACCOUNT_GROUP_TITLE + " =@title, "
                + DBHelper.ACCOUNT_GROUP_REMARK + " =@remark "
                + " WHERE " + DBHelper.PKID + " =@id; ",
                DBHelper.BASE_SQLITE_CONNECTION);

            while (reader.Read())
            {
                id = reader.GetInt32(0);
                cmd.Parameters.AddRange(new[] {
                    new SQLiteParameter("@id", id),
                    new SQLiteParameter("@title", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(1), oldKey), newKey)),
                    new SQLiteParameter("@remark", EncryptDecryptUtils.DES3Encrypt(EncryptDecryptUtils.DES3Decrypt(reader.GetString(2), oldKey), newKey))
                });
                ret += cmd.ExecuteNonQuery();
            }
            return ret != 0;
        }

        #endregion

        #region refresh progress bar

        private void SetLabelValue(string text)
        {
            if (label_current_process.InvokeRequired)
            {
                SetLabelValueCallback d = new SetLabelValueCallback(SetLabelValue);
                Invoke(d, new object[] { text });
            }
            else
            {
                label_current_process.Text = text;
            }
        }

        private void SetProgressBarValue(int value)
        {
            if (progressBar_main.InvokeRequired)
            {
                SetProgressBarValueCallback d = new SetProgressBarValueCallback(SetProgressBarValue);
                Invoke(d, new object[] { value });
            }
            else
            {
                progressBar_main.Value = value;
            }
        }

        private void SetFormClose()
        {
            CompleteCallback d = new CompleteCallback(OperationCompleted);
            Invoke(d, new object[] { });
        }

        #endregion
    }
}
